<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/hello' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="注意！只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
      <el-row>
        选择商品分类：
        <el-cascader
          v-model="threeId"
          :options="cateList"
          :props="addCateprop"
          @change="handleChange"
          clearable
        ></el-cascader>
      </el-row>
      <el-row>
        <!-- 选项卡 -->
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <!-- 动态参数列表 -->
          <el-tab-pane label="动态参数" name="many">
            <el-button
              type="primary"
              plain
              @click="openAddAttr"
              :disabled="cat_Pid.length != 3 ? true:false"
            >添加参数</el-button>
            <el-table :data="attrData" style="width: 100%" border>
              <el-table-column type="expand">
                <template slot-scope="props">
                  <el-tag
                    :key="e"
                    v-for="e in props.row.attr_vals"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(e,props.row)"
                  >{{e}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="inputVisible == props.row.attr_id"
                    v-model="inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(props.row)"
                    @blur="handleInputConfirm(props.row)"
                  ></el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(props.row.attr_id)"
                  >+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scopebtn1">
                  <div>
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-edit"
                      @click="editAttr(scopebtn1.row)"
                    ></el-button>
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="deleteAttr(scopebtn1.row)"
                    ></el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <!-- 静态属性列表 -->
          <el-tab-pane label="静态属性" name="only">
            <el-button
              type="primary"
              plain
              @click="openAddAttr"
              :disabled="cat_Pid.length != 3 ? true:false"
            >添加属性</el-button>
            <el-table :data="attrData" style="width: 100%" border>
              <el-table-column type="expand">
                <template slot-scope="props">
                  <el-tag
                    :key="e"
                    v-for="e in props.row.attr_vals"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(e,props.row)"
                  >{{e}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="inputVisible == props.row.attr_id"
                    v-model="inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(props.row)"
                    @blur="handleInputConfirm(props.row)"
                  ></el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(props.row.attr_id)"
                  >+ New Tag</el-button>
                </template>
              </el-table-column>

              <el-table-column type="index"></el-table-column>
              <el-table-column label="属性名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scopebtn">
                  <div>
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-edit"
                      @click="editAttr(scopebtn.row)"
                    ></el-button>
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="deleteAttr(scopebtn.row)"
                    ></el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-row>
    </el-card>

    <!-- //添加属性/参数对话框 -->
    <el-dialog
      :title="this.activeName =='many' ? `${flag}动态参数`:`${flag}静态属性` "
      :visible.sync="showAddAttr"
      :before-close="dialogClose"
    >
      <el-form :model="AddAttrFrom" :rules="attrRule" ref="addRef">
        <el-form-item :label="this.activeName =='many' ? '动态参数：':'静态属性：'" prop="attr_name">
          <el-input v-model="AddAttrFrom.attr_name" autocomplete="off" style="width:300px"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogClose">取 消</el-button>
        <el-button type="primary" @click="sendAttr" v-if="flag == '添加'">确 定</el-button>
        <el-button type="primary" @click="sendEditAttr" v-if="flag == '编辑'">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 标志符 0为添加对话框，1为编辑对话框
      flag: '添加',
      // 下拉框绑定数据
      threeId: '',
      cat_Pid: [],
      // 下拉框渲染数据
      cateList: [],
      // 联级选择器配置
      addCateprop: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 当前选项卡
      activeName: 'many',
      // 动态参数列表/静态属性列表
      attrData: [],
      // 参数列表配置
      dynamicTags: [],
      inputVisible: '',
      inputValue: '',
      // 添加参数标签请求数据绑定
      editQueryInfo: {
        attr_name: '',
        attr_sel: '',
        attr_vals: ''
      },
      // 显示添加参数对话框
      showAddAttr: false,
      // 添加参数对话框数据绑定
      AddAttrFrom: {
        attr_name: '',
        attr_sel: '',
        attr_vals: ''
      },
      // 当前修改的属性id
      attr_id: '',
      // 当前点击的tag标签所属的attr_id
      curreentId: '',
      // 验证add
      attrRule: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }, { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }]
      }
    }
  },
  methods: {
    async getAllCate() {
      // 获取所有分类请求
      let { data: res } = await this.$Http.getGoodsCategory()
      //   console.log(res)
      if (res.meta.status != 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },

    // 请求动态/静态参数
    async getAttributes() {
      if (!this.threeId) return
      let { data: res } = await this.$Http.getGoodsAttributes(this.threeId, this.activeName)
      if (res.meta.status != 200) return this.$message.error(res.meta.msg)
      //   console.log(res)
      res.data.forEach(e => {
        e.attr_vals = e.attr_vals.trim() === '' ? [] : e.attr_vals = e.attr_vals.split(' ')
      })
      this.attrData = res.data
      //   console.log(this.attrData)
    },
    // 编辑参数属性图标按钮
    editAttr(val) {
      this.flag = '编辑'
      this.AddAttrFrom.attr_name = val.attr_name
      this.AddAttrFrom.attr_sel = val.attr_sel
      this.attr_id = val.attr_id
      this.showAddAttr = true
    },
    // 编辑对话框确定按钮
    sendEditAttr() {
      console.log(this.AddAttrFrom)
      this.$refs.addRef.validate(async valid => {
        if (!valid) return
        let { data: res } = await this.$Http.editAttributes(this.threeId, this.attr_id, this.AddAttrFrom)
        if (res.meta.status != 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getAttributes()
        this.flag = '添加'
        this.dialogClose()
      })
    },
    // 删除参数
    deleteAttr(val) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let { data: res } = await this.$Http.deleteAttributes(val.cat_id, val.attr_id)
        if (res.meta.status != 200) return this.$message.error(res.meta.msg)
        this.getAttributes()
        this.$message.success('删除成功！')
      }).catch(() => {
        this.$message.info('已取消删除!')
      })
    },
    // 监听下拉框
    handleChange(val) {
      if (!val) return (this.attrData = [])
      this.cat_Pid = val
      this.threeId = val[val.length - 1]
      this.getAttributes()
    },
    // 监听选项卡
    handleClick(tab, event) {
      this.getAttributes()
    },
    // 打开添加参数对话框
    openAddAttr() {
      this.showAddAttr = true
      this.AddAttrFrom.attr_name = ''
    },
    // 确定添加动态参数/静态属性（table左上角按钮）
    sendAttr() {
      this.$refs.addRef.validate(async valid => {
        if (!valid) return
        this.AddAttrFrom.attr_sel = this.activeName
        let { data: res } = await this.$Http.addAttributes(this.threeId, this.AddAttrFrom)
        // console.log(res)
        if (res.meta.status != 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getAttributes()
        this.dialogClose()
      })
    },
    // 弹出对话框关闭事件
    dialogClose() {
      this.showAddAttr = false
      this.AddAttrFrom.attr_name = ''
      this.$refs.addRef.resetFields()
      this.flag = '添加'
    },
    // tag标签监听关闭事件
    async handleClose(e, val) {
      // this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
      val.attr_vals.splice(val.attr_vals.indexOf(e), 1)
      this.editQueryInfo.attr_name = val.attr_name
      this.editQueryInfo.attr_vals = val.attr_vals.join(',')
      this.editQueryInfo.attr_sel = val.attr_sel
      let { data: res } = await this.$Http.editAttributes(val.cat_id, val.attr_id, this.editQueryInfo)
    },
    // 显示添加参数输入框
    showInput(val) {
      this.inputVisible = val
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 输入完成触发事件
    async handleInputConfirm(val) {
      this.inputVisible = false
      if (this.inputValue.trim() === '') return (this.inputValue = '')
      if (val.attr_vals.indexOf(this.inputValue) != -1) {
        this.$message.error(`已存在${this.inputValue}项目！`)
        this.inputValue = ''
        return
      }
      val.attr_vals.push(this.inputValue)
      //   let newArr =[...new Set(val.attr_vals)]
      //   console.log(newArr);
      this.editQueryInfo.attr_name = val.attr_name
      this.editQueryInfo.attr_vals = val.attr_vals.join(',')
      this.editQueryInfo.attr_sel = val.attr_sel
      this.inputValue = ''
      // 添加tag标签调用添加参数接口
      let { data: res } = await this.$Http.editAttributes(val.cat_id, val.attr_id, this.editQueryInfo)
    }
  },
  created() {
    this.getAllCate()
    this.getAttributes()
  }
}
</script>
<style lang='less' scoped>
.el-row {
  margin: 15px 0;
}
.el-cascader {
  width: 500px;
}
.el-input {
  width: 120px;
}
.el-tag {
  margin-right: 10px;
  margin-top: 10px;
}
</style>
